import { Form, Input, Select, TreeSelect } from 'antd';
import { useContext, useEffect } from 'react';
import { WorkflowSwitchContext } from '../common';
import { WorkflowSwitchAPI } from '../common/type';
import { getTenantID } from '@/utils';
import { ILoadMapTypeAll } from '@/common';

export const WorkflowNodesTable: React.FC<WorkflowSwitchAPI.IWorkflowNodesTable> = ({
  workFlowNodesList,
  userDataInfoObj,
  ordinaryUserInfoObj,
  changePostCheckID,
}) => {
  const { prefixCls, nodeFlowForm, businessInfoObj } = useContext(WorkflowSwitchContext);
  /**
   * 处理普通节点处理切换岗位时改变用户默认值
   * @param defauId 节点数据中的默认值
   * @param userList 当前选中岗位下的用户数据
   * @param useFormName 当前节点的用户表单名称
   */
  const userCheckZeroDefault = (defauId: string, userList: any, useFormName: string) => {
    let selectUserObj: any = userList?.find((defaItem: any) => {
      return defaItem?.id == defauId;
    });
    if (selectUserObj && JSON.stringify(selectUserObj) != '{}') {
      nodeFlowForm?.setFieldsValue({
        [useFormName]: defauId,
      });
    } else {
      nodeFlowForm?.setFieldsValue({
        [useFormName]: selectUserObj?.id,
      });
    }
  };

  /** 不显示发起节点 */
  const notShowStartNode = (info: Record<string, any>) => {
    let notCss: React.CSSProperties = {};
    if (info?.dealPositionID == 'originPositionID,') {
      notCss['display'] = 'none';
    }

    if (!businessInfoObj.relateDepartmentID && info?.taskName.indexOf('本单位归口') > -1) {
      notCss['display'] = 'none';
    }

    if (
      !businessInfoObj.busiDepartmentID &&
      info?.taskName.indexOf('归口') > -1 &&
      info?.taskName.indexOf('本单位归口') < 0 &&
      info?.taskName !== '办公室主任归口审批'
    ) {
      notCss['display'] = 'none';
    }
    if (!businessInfoObj.relateDepartmentID && info?.taskName.indexOf('相关') > -1) {
      notCss['display'] = 'none';
    }

    if (
      businessInfoObj?.allotType == 1 &&
      (info?.taskName.indexOf('接收方部门/团队资管员审批') > -1 || info?.taskName.indexOf('接收方部门/团队领导审批') > -1)
    ) {
      notCss['display'] = 'none';
    }

    if (businessInfoObj?.assetStorageMaterialType == '0' && info?.taskName.indexOf('资产专责复核') > -1) {
      notCss['display'] = 'none';
    }

    /**
     * 屏蔽节点名称 【财务资产部专责复核】

      businessType 【领用 100199031011】【退库 100199031013】

      判断条件 如果详情对象（businessInfoObj）的 【applyType == '2'】则屏蔽流程节点
     */

    if (
      businessInfoObj?.businessType == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1011` ||
      businessInfoObj?.businessType == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1013`
    ) {
      if (businessInfoObj?.applyType == 2 && info?.taskName.indexOf('财务资产部专责复核') > -1) {
        notCss['display'] = 'none';
      }
    }

    /**
     * 材料入库流程过滤资产流程节点
     */
    if (businessInfoObj?.materialType == 0 && info?.taskName.indexOf('资产入库') > -1) {
      notCss['display'] = 'none';
    }

    /**
     * 资产入库流程过滤材料流程节点
     */
    if (businessInfoObj?.materialType == 1 && info?.taskName.indexOf('材料入库') > -1) {
      notCss['display'] = 'none';
    }

    /**
     * 采购申请流程
     */
    if (businessInfoObj?.businessType == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1003`) {
      if (info?.taskName.indexOf('归口') > -1) {
        notCss['display'] = 'true';
      }
    }

    return notCss;
  };

  return (
    <div
      style={{
        width: '100%',
        height: '100%',
        overflow: 'hidden',
        padding: '15px',
      }}
    >
      <table cellSpacing="0" cellPadding="0" className={prefixCls + 'workflowNodesTableTitle'}>
        <thead className={prefixCls + 'workflowNodesTableTitle-tableTheadBox'}>
          <tr>
            <th style={{ width: '10%' }}>任务编号</th>
            <th style={{ width: '20%' }}>任务名称</th>
            <th style={{ width: '20%' }}>办理人岗位</th>
            <th style={{ width: '20%' }}>办理人</th>
            <th style={{ width: '10%' }}>是否会签</th>
          </tr>
        </thead>
      </table>
      <div
        className={prefixCls + 'workflowTbodyRootDiv'}
        style={{
          maxHeight: `${document.body.clientHeight * 0.4}px`,
        }}
      >
        <table cellSpacing="0" cellPadding="0" className={prefixCls + 'workflowNodesTableTbody'}>
          <tbody className={prefixCls + 'workflowNodesTableTbody-tableTbodyBox'}>
            {workFlowNodesList?.map((pItem: any, pIndex: number) => {
              const displayCss: React.CSSProperties = notShowStartNode(pItem);
              return (
                <tr style={{ ...displayCss }} key={`${pIndex}${Math.random()}`}>
                  <td style={{ width: '10%' }}>{pItem?.seq}</td>
                  <td style={{ width: '20%' }}>{pItem.taskName}</td>

                  <td style={{ width: '20%', padding: '0px' }}>
                    {pItem?.dealPositionID == 'originPositionID,' ? (
                      <Form.Item
                        name={'paramObject[' + pIndex + '].dealPositionID[' + '0' + ']'}
                        label=""
                        initialValue={pItem?.postValues?.[0]?.postId}
                        key={`${0}${Math.random()}`}
                      >
                        <Select placeholder="请选择发起岗位" bordered={false} disabled={true} showArrow={false}>
                          <Select.Option key={pItem?.postValues?.[0]?.postId} value={pItem?.postValues?.[0]?.postId}>
                            {pItem?.postValues?.[0]?.postName}
                          </Select.Option>
                        </Select>
                      </Form.Item>
                    ) : pItem?.taskIsSign == 0 ? (
                      <>
                        <Form.Item
                          key={`${0}${Math.random()}`}
                          name={'paramObject[' + pIndex + '].dealPositionID[' + '0' + ']'}
                          label=""
                          initialValue={pItem?.posTreeData.length && displayCss?.display != 'none' ? undefined : pItem?.postValues?.[0]?.postId}
                        >
                          {pItem?.posTreeData.length ? (
                            <TreeSelect
                              placeholder="请选择"
                              treeData={pItem?.posTreeData}
                              size="small"
                              showArrow={true}
                              fieldNames={{
                                label: 'title',
                                value: 'id',
                                children: 'children',
                              }}
                              bordered={false}
                              showSearch={true}
                              treeNodeFilterProp={'text'}
                              allowClear={false}
                              onSelect={(value: any, node) => {
                                const selectId = value;
                                pItem.userList = userDataInfoObj[selectId];
                                changePostCheckID(pItem?.taskNode, selectId); //保存切换的岗位id 以改变用户数据
                                let defaultId = '';
                                if (pItem.userList && pItem.userList?.length == 1) {
                                  defaultId = pItem.userList[0]?.id || '';
                                }
                                userCheckZeroDefault(defaultId, userDataInfoObj?.[selectId], 'paramObject[' + pIndex + '].dealerID[' + '0' + ']');
                              }}
                            />
                          ) : (
                            <Select
                              placeholder="请选择办理岗位"
                              bordered={false}
                              disabled={true}
                              showArrow={false}
                              showSearch
                              optionFilterProp={'searchtitle'}
                              onSelect={(selectId: any) => {
                                changePostCheckID(pItem?.taskNode, selectId); //保存切换的岗位id 以改变用户数据
                                const postSelectIndex: any = pItem?.postValues?.findIndex((selectItem: any) => {
                                  //获取选脏鞥你岗位下标
                                  return selectItem?.postId == selectId;
                                });
                                if (postSelectIndex != -1) {
                                  pItem.userList = userDataInfoObj[selectId];
                                  let defaultId = pItem?.postValues?.[postSelectIndex]?.defaultDealer;
                                  if (pItem.userList && pItem.userList?.length == 1) {
                                    defaultId = pItem.userList[0]?.id || '';
                                  }
                                  userCheckZeroDefault(defaultId, userDataInfoObj?.[selectId], 'paramObject[' + pIndex + '].dealerID[' + '0' + ']');
                                }
                              }}
                            >
                              {pItem?.postValues?.map((itemPost: any) => {
                                return (
                                  <Select.Option key={itemPost?.postId} value={itemPost?.postId} searchtitle={itemPost?.postName}>
                                    {itemPost?.postName}
                                  </Select.Option>
                                );
                              })}
                            </Select>
                          )}
                        </Form.Item>
                      </>
                    ) : pItem?.taskIsSign == 1 ? (
                      pItem?.posTreeData.length ? (
                        <>
                          <Form.Item
                            key={`${0}${Math.random()}`}
                            name={'paramObject[' + pIndex + '].dealPositionID[' + '0' + ']'}
                            label=""
                            initialValue={pItem?.posTreeData.length && displayCss?.display != 'none' ? undefined : pItem?.postValues?.[0]?.postId}
                          >
                            <TreeSelect
                              placeholder="请选择"
                              treeData={pItem?.posTreeData}
                              size="small"
                              showArrow={true}
                              fieldNames={{
                                label: 'title',
                                value: 'id',
                                children: 'children',
                              }}
                              bordered={false}
                              showSearch={true}
                              treeNodeFilterProp={'text'}
                              allowClear={false}
                              onSelect={(value: any, node) => {
                                const selectId = value;
                                pItem.userList = userDataInfoObj[selectId];
                                changePostCheckID(pItem?.taskNode, selectId); //保存切换的岗位id 以改变用户数据
                                let defaultId = '';
                                if (pItem.userList && pItem.userList?.length == 1) {
                                  defaultId = pItem.userList[0]?.id || '';
                                }
                                userCheckZeroDefault(defaultId, userDataInfoObj?.[selectId], 'paramObject[' + pIndex + '].dealerID[' + '0' + ']');
                              }}
                            />
                          </Form.Item>
                        </>
                      ) : (
                        <>
                          {pItem?.postValues?.map((itemChildren: any, indexChildren: number) => {
                            return (
                              <Form.Item
                                key={`${0}${Math.random()}`}
                                name={'paramObject[' + pIndex + '].dealPositionID[' + indexChildren + ']'}
                                label=""
                                initialValue={itemChildren?.postId}
                                style={{
                                  borderBottom: pItem?.postValues?.length - 1 == indexChildren ? 0 : '1px solid #d7d7d7',
                                }}
                              >
                                <Select
                                  placeholder="请选择办理岗位"
                                  bordered={false}
                                  showArrow={false}
                                  showSearch
                                  optionFilterProp={'searchtitle'}
                                  disabled={true}
                                >
                                  <Select.Option key={itemChildren?.postId} value={itemChildren?.postId} searchtitle={itemChildren?.postName}>
                                    {itemChildren?.postName}
                                  </Select.Option>
                                </Select>
                              </Form.Item>
                            );
                          })}
                        </>
                      )
                    ) : (
                      <></>
                    )}
                  </td>

                  {/* 选择人员 */}
                  <td style={{ width: '20%', padding: '0px' }}>
                    {pItem?.dealPositionID == 'originPositionID,' ? (
                      <Form.Item
                        key={`0${Math.random()}`}
                        name={'paramObject[' + pIndex + '].dealerID[' + '0' + ']'}
                        label=""
                        initialValue={pItem?.postValues?.[0]?.defaultDealer}
                        rules={[
                          {
                            required: true,
                            message: '请选择发起人',
                          },
                        ]}
                      >
                        <Select placeholder="请选择发起人" bordered={false} disabled={true} showArrow={false}>
                          <Select.Option key={pItem?.postValues?.[0]?.defaultDealer} value={pItem?.postValues?.[0]?.defaultDealer}>
                            {pItem?.postValues?.[0]?.defaultDealerName}
                          </Select.Option>
                        </Select>
                      </Form.Item>
                    ) : pItem?.taskIsSign == 0 ? (
                      <>
                        <Form.Item
                          key={`${0}${Math.random()}`}
                          name={'paramObject[' + pIndex + '].dealerID[' + '0' + ']'}
                          label=""
                          initialValue={pItem?.posTreeData.length && displayCss?.display != 'none' ? undefined : pItem?.postValues?.[0]?.defaultDealer}
                          rules={[
                            {
                              required: true,
                              message: '请选择办理人',
                            },
                          ]}
                        >
                          <Select
                            placeholder="请选择"
                            bordered={false}
                            showSearch
                            optionFilterProp={'searchtitle'}
                            // disabled={true}
                          >
                            {(pItem?.posTreeData.length
                              ? pItem.userList
                                ? pItem.userList
                                : []
                              : userDataInfoObj?.[ordinaryUserInfoObj?.[pItem?.taskNode]]
                            )?.map((useItem: any) => {
                              return (
                                <Select.Option key={useItem?.id} value={useItem?.id} searchtitle={useItem?.realName}>
                                  {useItem?.realName}
                                </Select.Option>
                              );
                            })}
                          </Select>
                        </Form.Item>
                      </>
                    ) : pItem?.taskIsSign == 1 ? (
                      pItem?.posTreeData.length ? (
                        <Form.Item
                          key={`${0}${Math.random()}`}
                          name={'paramObject[' + pIndex + '].dealerID[' + '0' + ']'}
                          label=""
                          initialValue={pItem?.posTreeData.length && displayCss?.display != 'none' ? undefined : pItem?.postValues?.[0]?.defaultDealer}
                          rules={[
                            {
                              required: true,
                              message: '请选择办理人',
                            },
                          ]}
                        >
                          <Select
                            placeholder="请选择"
                            bordered={false}
                            showSearch
                            optionFilterProp={'searchtitle'}
                            // disabled={true}
                          >
                            {(pItem?.posTreeData.length
                              ? pItem.userList
                                ? pItem.userList
                                : []
                              : userDataInfoObj?.[ordinaryUserInfoObj?.[pItem?.taskNode]]
                            ).map((useItem: any) => {
                              return (
                                <Select.Option key={useItem?.id} value={useItem?.id} searchtitle={useItem?.realName}>
                                  {useItem?.realName}
                                </Select.Option>
                              );
                            })}
                          </Select>
                        </Form.Item>
                      ) : (
                        <>
                          {pItem?.postValues?.map((itemChildren: any, indexChildren: number) => {
                            return (
                              <Form.Item
                                key={`${indexChildren}${Math.random()}`}
                                name={'paramObject[' + pIndex + '].dealerID[' + indexChildren + ']'}
                                label=""
                                initialValue={itemChildren?.defaultDealer || itemChildren?.checkUserList?.[0]?.id}
                                style={{
                                  borderBottom: pItem?.postValues?.length - 1 == indexChildren ? 0 : '1px solid #d7d7d7',
                                }}
                                rules={[
                                  {
                                    required: true,
                                    message: '请选择办理人',
                                  },
                                ]}
                              >
                                <Select
                                  placeholder="请选择办理人"
                                  bordered={false}
                                  showSearch
                                  optionFilterProp={'searchtitle'}
                                  // disabled={true}
                                >
                                  {itemChildren?.checkUserList?.map((useItem: any) => {
                                    return (
                                      <Select.Option key={useItem?.id} value={useItem?.id} searchtitle={useItem?.realName}>
                                        {useItem?.realName}
                                      </Select.Option>
                                    );
                                  })}
                                </Select>
                              </Form.Item>
                            );
                          })}
                        </>
                      )
                    ) : (
                      <></>
                    )}
                  </td>

                  <td style={{ width: '10%', color: pItem?.taskIsSign == 0 ? '#ff4d4f' : '#52c41a' }}>
                    {pItem?.taskIsSign == 0 && '否'}
                    {pItem?.taskIsSign == 1 && '是'}
                    <Form.Item
                      name={'paramObject[' + pIndex + '].taskIsSign'}
                      label=""
                      initialValue={pItem?.dealPositionID == 'originPositionID,' ? '2' : pItem?.taskIsSign}
                      className={'displayNoneNodeWorkFlow'}
                    >
                      <Input type="hidden" />
                    </Form.Item>

                    <Form.Item name={'paramObject[' + pIndex + '].seq'} label="" initialValue={pItem?.seq} className={'displayNoneNodeWorkFlow'}>
                      <Input type="hidden" />
                    </Form.Item>

                    <Form.Item name={'paramObject[' + pIndex + '].procDefID'} label="" initialValue={pItem?.procDefID} className={'displayNoneNodeWorkFlow'}>
                      <Input type="hidden" />
                    </Form.Item>

                    <Form.Item name={'paramObject[' + pIndex + '].orderID'} label="" initialValue={pItem?.orderID} className={'displayNoneNodeWorkFlow'}>
                      <Input type="hidden" />
                    </Form.Item>

                    <Form.Item name={'paramObject[' + pIndex + '].taskNode'} label="" initialValue={pItem?.taskNode} className={'displayNoneNodeWorkFlow'}>
                      <Input type="hidden" />
                    </Form.Item>

                    <Form.Item name={'paramObject[' + pIndex + '].dealerNum'} label="" initialValue={pItem?.dealerNum} className={'displayNoneNodeWorkFlow'}>
                      <Input type="hidden" />
                    </Form.Item>

                    <Form.Item name={'paramObject[' + pIndex + '].taskName'} label="" initialValue={pItem?.taskName} className={'displayNoneNodeWorkFlow'}>
                      <Input type="hidden" />
                    </Form.Item>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
};
